import { ref, onMounted, onUnmounted } from 'vue';
import io, { Socket } from 'socket.io-client';

export function useSocket() {
  const isConnected = ref(false);
  const clientCount = ref(0);
  const messages = ref<Array<{
    text: string;
    timestamp: Date | string;
    incoming: boolean;
    type?: string;
  }>>([]);
  const messageText = ref('');
  let socket: Socket | null = null;

  // 建立连接
  const connect = () => {
    if (socket) socket.disconnect();

    // 连接服务器
    socket = io('http://localhost:3000', {
      autoConnect: true,
      withCredentials: true
    });

    // 监听连接成功
    socket.on('connect', () => {
      isConnected.value = true;
      console.log('连接成功');
    });

    // 监听断开连接
    socket.on('disconnect', () => {
      isConnected.value = false;
      console.log('连接断开');
    });

    // 监听服务器消息
    socket.on('message', (data: any) => {
      console.log('收到服务器消息:', data);
      
      // 处理时间戳
      const timestamp = typeof data.timestamp === 'string' 
        ? new Date(data.timestamp) 
        : data.timestamp;

      // 添加到消息列表
      messages.value.push({
        text: data.text || '无内容',
        timestamp,
        incoming: true,
        type: data.type
      });

      scrollToBottom();
    });

    // 监听在线人数更新
    socket.on('clientCount', (count: number) => {
      clientCount.value = count;
    });

    // 监听连接错误
    socket.on('connect_error', (err) => {
      console.error('Socket连接错误:', err);
    });
  };

  // 发送消息
  const sendMessage = () => {
    if (!socket || !isConnected.value || !messageText.value.trim()) return;
    
    const text = messageText.value.trim();
    socket.emit('message', { text, timestamp: new Date() });
    
    // 添加到本地消息列表
    messages.value.push({
      text,
      timestamp: new Date(),
      incoming: false
    });
    
    messageText.value = '';
    scrollToBottom();
  };

  // 格式化时间
  const formatTime = (time: Date | string) => {
    try {
      return new Date(time).toLocaleTimeString();
    } catch (e) {
      console.error('时间格式化错误:', e);
      return '时间错误';
    }
  };

  // 滚动到最新消息
  const scrollToBottom = () => {
    setTimeout(() => {
      const messageList = document.querySelector('.message-list');
      if (messageList) {
        messageList.scrollTop = messageList.scrollHeight;
      }
    }, 0);
  };

  // 组件挂载时连接
  onMounted(connect);

  // 组件卸载时断开连接
  onUnmounted(() => {
    if (socket) {
      socket.disconnect();
      socket = null;
    }
  });

  return {
    isConnected,
    clientCount,
    messages,
    messageText,
    sendMessage,
    formatTime,
    connect
  };
}